<template>
  <div>
    <a-spin :spinning="loading">
      <a-card>
        <div slot="title" class="assign-titie-div">
          <div class="assign-tiltle-div-label">
            新增分派
          </div>
          <div class="assign-tiltle-div-operate">
            <a-form layout="inline" style="width: 100%;font-weight: bold">
              <a-row :gutter="48" style="width: 100%">
                <a-col @click.stop="() => {}" :md="8" :sm="24">
                  <a-form-item label="待分派案号：" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
                    <a-input v-model="personParam.needAssignCode" style="width: 240px;"  placeholder="请输入案号" allowClear />
                  </a-form-item>
                </a-col>
                <a-col @click.stop="() => {}" :md="8" :sm="24">
                  <a-form-item label="已分派案号：" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
                    <a-input v-model="personParam.assignCode" style="width: 240px;"  placeholder="请输入案号" allowClear />
                  </a-form-item>
                </a-col>
                <a-col @click.stop="() => {}" :md="8" :sm="24">
                  <div style="padding-left: 70px">
                    <a-button type="primary" @click="queryUndoList()">查询</a-button>
                    <a-button @click="resetQuery()" style="margin-left: 20px">重置</a-button>
                  </div>
                </a-col>
              </a-row>
              <a-row :gutter="48" style="width: 100%;margin-top: 16px;">
                <a-col @click.stop="() => {}" :md="8" :sm="24">
                  <a-form-item label="承办人：" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
                    <a-tree-select
                      v-if="treeData"
                      style="width: 240px; font-weight: normal"
                      show-search
                      tree-node-filter-prop="title"
                      placeholder="请选择承办人"
                      v-model="personParam.firstPersonId"
                      :replaceFields="{ children: 'children', title: 'name', key: 'id',value: 'id' }"
                      :tree-data="treeData"
                      allow-clear
                      tree-default-expand-all
                    ></a-tree-select>
                  </a-form-item>
                </a-col>

                <a-col @click.stop="() => {}" :md="8" :sm="24">
                  <a-form-item label="协办人：" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
                    <a-tree-select
                      v-if="treeData"
                      style="width: 240px; font-weight: normal"
                      show-search
                      tree-node-filter-prop="title"
                      placeholder="请选择协办人"
                      v-model="personParam.secondPersonId"
                      :replaceFields="{ children: 'children', title: 'name', key: 'id',value: 'id' }"
                      :tree-data="treeData"
                      allow-clear
                      tree-default-expand-all
                    ></a-tree-select>
                  </a-form-item>
                </a-col>

                <a-col @click.stop="() => {}" :md="8" :sm="24">
                  <a-form-item label="辅助人：" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
                    <a-tree-select
                      v-if="treeData"
                      style="width: 240px; font-weight: normal"
                      show-search
                      tree-node-filter-prop="title"
                      placeholder="请选择辅助人"
                      v-model="personParam.thirdPersonId"
                      :replaceFields="{ children: 'children', title: 'name', key: 'id',value: 'id' }"
                      :tree-data="treeData"
                      allow-clear
                      tree-default-expand-all
                    ></a-tree-select>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </div>
        </div>
        <div class="assign-operate-div">
          <a-transfer
            :data-source="assignData"
            :list-style="{
              height: '550px',
            }"
            :titles="transferTitle"
            :target-keys="targetKeys"
            :disabled="disabled"
            :show-search="true"
            :filter-option="(inputValue, item) => item.title.indexOf(inputValue) !== -1"
            :show-select-all="false"
            :operations="['案件分派(A)', '分派退回(R)']"
            @change="onChange"
            @search="handleSearch"
          >
            <template
              slot="children"
              slot-scope="{
                props: { direction, filteredItems, selectedKeys, disabled: listDisabled },
                on: { itemSelectAll, itemSelect },
              }"
            >
              <a-table
                :row-selection="
                  getRowSelection({ disabled: listDisabled, selectedKeys, itemSelectAll, itemSelect })
                "
                rowKey="id"
                bordered
                :scroll="{ x: 1000 }"
                :columns="direction === 'left' ? leftColumns : rightColumns"
                :data-source="filteredItems"
                :style="{ pointerEvents: listDisabled ? 'none' : null }"
                :custom-row="
                  ({ key, disabled: itemDisabled }) => ({
                    on: {
                      click: () => {
                        if (itemDisabled || listDisabled) return;
                        itemSelect(key, !selectedKeys.includes(key));
                      },
                    },
                  })
                "
              >
                <div
                  slot="targetnameSlot"
                  slot-scope="text, record"
                  class="beyond_hiding"
                  style="width: 100%; text-align: left"
                >
                  <a-tooltip placement="topLeft">
                    <template slot="title">
                      <span>{{ record.targetname }}</span>
                    </template>
                    {{ record.targetname }}
                  </a-tooltip>
                </div>

                <div slot="subtimeSlot" slot-scope="subtime" class="beyond_hiding" style="width: 100%">
                  {{ subtime | getTimeFormat('YYYY年M月D日') }}
                </div>
              </a-table>
            </template>
          </a-transfer>
        </div>
      </a-card>
    </a-spin>
  </div>
</template>

<script>
import CommonHeadQueryComponent from '@/views/accept/component/CommonHeadQueryComponent.vue'
import CommonHeaderComponent from '@/views/accept/component/CommonHeaderComponent.vue'
import { ADMREVIEW_DEPART } from '@/utils/custom/custom-depart.js'
import { queryUserTreeByDepartids } from '@/api/base/ha_user'
import { CommonAssignQuery } from '@/api/workflow/wf_CompreQuery.js'
import { APP_USER, APP_DEPT } from '@/store/mutation-types.js'
import storage from 'store'
import { Tp_biztype } from '@/enumeration/Tp_biztype'
import { updateFirstAndSecondPerson, resetFirstAndSecondPerson } from '@/api/supervise/apl_supervise.js'
import { claimTaskBatch, cleanClaimTask } from '@/api/workflow/wf_MyStartInstance.js'
const leftTableColumns = [
 {
    title: '案号',
    dataIndex: 'acceptcode',
    key: 'acceptcode',
    width: 250,
    align: 'center'
  },
  {
    title: '申请人名称',
    dataIndex: 'applyname',
    key: 'applyname',
    width: 200,
    align: 'center',
    scopedSlots: { customRender: 'applynameSlot' }
  },
  {
    title: '被申请人名称',
    dataIndex: 'targetname',
    key: 'targetname',
    width: 250,
    align: 'center',
    scopedSlots: { customRender: 'targetnameSlot' }
  },
  {
    title: '承办人',
    width: 150,
    key: 'dealName',
    dataIndex: 'dealName',
    align: 'center',
    scopedSlots: { customRender: 'dealNameSlot' }
  },
  {
    title: '申请时间',
    dataIndex: 'subtime',
    key: 'subtime',
    width: 150,
    align: 'center',
    scopedSlots: { customRender: 'subtimeSlot' }
  }
]
const rightTableColumns = [
{
    title: '案号',
    dataIndex: 'acceptcode',
    key: 'acceptcode',
    width: 250,
    align: 'center'
  },
  {
    title: '申请人名称',
    dataIndex: 'applyname',
    key: 'applyname',
    width: 200,
    align: 'center',
    scopedSlots: { customRender: 'applynameSlot' }
  },
  {
    title: '被申请人名称',
    dataIndex: 'targetname',
    key: 'targetname',
    width: 250,
    align: 'center',
    scopedSlots: { customRender: 'targetnameSlot' }
  },
  {
    title: '承办人',
    width: 150,
    key: 'dealName',
    dataIndex: 'dealName',
    align: 'center',
    scopedSlots: { customRender: 'dealNameSlot' }
  },
  {
    title: '申请时间',
    dataIndex: 'subtime',
    key: 'subtime',
    width: 150,
    align: 'center',
    scopedSlots: { customRender: 'subtimeSlot' }
  }
]

export default {
  data () {
    return {
      superviseDealNum: null,
      loading: false,
      personParam: {
        needAssignCode: undefined, // 待分派案号
        assignCode: undefined, // 已分派案号
        firstPersonId: undefined,
        firstPersonName: undefined,
        secondPersonId: undefined,
        secondPersonName: undefined,
        thirdPersonId: undefined,
        thirdPersonName: undefined
      },
      ADMREVIEW_DEPART: ADMREVIEW_DEPART, // 行政复议相关科室
      Tp_biztype: Tp_biztype,

      treeData: [],
      departList: ADMREVIEW_DEPART,
      type: 'user',

      currentUser: storage.get(APP_USER), // 登录人信息
      currentDept: storage.get(APP_DEPT), // 登录人部门
      leftColumns: leftTableColumns,
      rightColumns: rightTableColumns,
      assignData: [],
      targetKeys: [],
      disabled: false,
      rootSubmenuKeys: [], // transfer组件变量
      openKeys: [], // transfer组件变量
      selectAssignData: [], // 选中数据
      rollBackData: [], // 退回数据

      queryParam: {
        f_code: '', // 案号
        f_code_other: '', // 案号
        f_applyname: '', // 申请人
        f_targetname: '', // 被申请人
        accepttime_start: null, // 开始时间
        accepttime_end: null, // 结束时间
        finishDate_start: undefined, // 办结完成开始日期
        finishDate_end: undefined, // 办结结束开始日期
        f_source: undefined, // 来源
        matid: '100000_360100-000201005000-QT-002-02', // matid
        pageNumber: 1,
        pageSize: 20,
        order: 'desc',
        isAssigned: null, // 是否分派
        category: 'evidence', // 环节标识
        userid: '' // 用户id
      },
      treeInfo: null,
      transferTitle: []
    }
  },
  components: {
    deptUserTree: () => import('@/views/base/DeptUserTree.vue'),
    CommonHeadQueryComponent,
    CommonHeaderComponent
  },
  created () {
    this.findTreeData()
    this.queryUndoList()
  },
  mounted () {
    this.findTreeData()
    this.queryUndoList()
  },
  watch: {
    'personParam.firstPersonId': {
      handler (newValue, oldVal) {
        if (newValue) {
          if (newValue == this.personParam.secondPersonId || newValue == this.personParam.thirdPersonId) {
            this.$message.warning('承办人，协办人，辅助人不能为同一个人')
            this.personParam.firstPersonId = null
          } else {
            this.recursiveFilter(this.treeData, newValue)
            if (this.treeInfo) {
              this.personParam.firstPersonName = this.treeInfo.name
            }
          }
        }
      },
      deep: true // 深度监听
    },
    'personParam.secondPersonId': {
      handler (newValue, oldVal) {
        if (newValue) {
          if (newValue == this.personParam.firstPersonId || newValue == this.personParam.thirdPersonId) {
            this.$message.warning('承办人，协办人，辅助人不能为同一个人')
            this.personParam.secondPersonId = null
          } else {
            this.recursiveFilter(this.treeData, newValue)
            if (this.treeInfo) {
              this.personParam.secondPersonName = this.treeInfo.name
            }
          }
        }
      },
      deep: true // 深度监听
    },
    'personParam.thirdPersonId': {
      handler (newValue, oldVal) {
        if (newValue) {
          if (newValue == this.personParam.firstPersonId || newValue == this.personParam.secondPersonId) {
            this.$message.warning('承办人，协办人，辅助人不能为同一个人')
            this.personParam.thirdPersonId = null
          } else {
            this.recursiveFilter(this.treeData, newValue)
            if (this.treeInfo) {
              this.personParam.thirdPersonName = this.treeInfo.name
            }
          }
        }
      },
      deep: true // 深度监听
    }
  },
  methods: {
    // 设置对应的枚举值
    setCompreEnumData (listData) {
      if (listData && listData.length > 0) {
        for (var index = 0; index < listData.length; index++) {
          const item = listData[index]
          if (item) {
            // 承办人
            let dealNames = []
            dealNames.push(item.firstname || item.firstname_bs)
            dealNames.push(item.secondname || item.secondname_bs)
            dealNames = dealNames.filter(el => el != null && el != '')
            item.dealName = dealNames.join('，')
            item.step_text = item.step ? Array.from(new Set(item.step.split(','))).join() : ''
          }
        }
      }
    },
    resetQuery () {
      this.queryParam = {
        f_code: '', // 案号
        f_code_other: '', // 案号
        f_applyname: '', // 申请人
        f_targetname: '', // 被申请人
        accepttime_start: null, // 开始时间
        accepttime_end: null, // 结束时间
        finishDate_start: undefined, // 办结完成开始日期
        finishDate_end: undefined, // 办结结束开始日期
        f_source: undefined, // 来源
        matid: '100000_360100-000201005000-QT-002-02', // matid
        pageNumber: 1,
        pageSize: 20,
        order: 'desc',
        isAssigned: null, // 是否分派
        category: 'evidence', // 环节标识
        userid: '' // 用户id
      }
      this.personParam.needAssignCode = null
      this.personParam.assignCode = null
      this.queryUndoList()
    },
    async queryUndoList () {
      // queryParam.userid = this.currentUser.userId
      if (this.personParam.needAssignCode) {
        this.queryParam.f_code = this.personParam.needAssignCode.trim()
      }
      if (this.personParam.assignCode) {
        this.queryParam.f_code_other = this.personParam.assignCode.trim()
      }
      this.loading = true
      this.assignData = []
      this.targetKeys = []
      const res = await CommonAssignQuery(this.queryParam).catch(err => {
        this.assignData = []
        console.log(err, '获取数据失败')
      }).finally(() => {
        this.loading = false
      })
      if (res.code !== 0) {
        this.$message.error('获取数据失败')
      } else {
        this.assignData = res.data.records
        this.setCompreEnumData(this.assignData)
        this.assignData.forEach(el => {
          el.key = el.id
          el.title = el.acceptcode
          el.description = el.acceptcode
          el.disabled = false
        })
        console.log('获取数据', this.assignData)
        let todoCount = 0
        for (let index = 0; index < this.assignData.length; index++) {
          if (this.assignData[index].firstid && this.assignData[index].secondid) {
            this.targetKeys.push(this.assignData[index].key)
          } else {
            todoCount++
          }
        }
        let allCount = res.data.total
        let doneCount = allCount - todoCount
        this.$emit('setTotal', todoCount)
        this.transferTitle = [`待分派（${todoCount}）`, `已分派（${doneCount}）`]
        console.log('已选择', this.targetKeys)
      }
    },

    // 查询树下拉的数据
    async findTreeData () {
      const res = await queryUserTreeByDepartids(this.departList)
      if (res.code === 0 && res.data) {
        let data = res.data
        if (this.filterOrgIds && this.filterOrgIds.length > 0) {
          data = data.filter(item => this.filterOrgIds.includes(item.id))
          this.expandedKeys = this.expandedKeys.concat(this.filterOrgIds)
        }
        console.log('转换前的数据', data)
        data = this.fixSlot(data)
        this.treeData = this.renderTreeNodes(data)
        console.log('转换后的数据', this.treeData)
      }
    },
    fixSlot (data) {
      // 构造slot
      return data.map((item) => {
        if (item.type === 'user') {
          item.scopedSlots = { avatar: item.avatar }
          if (item.children) {
            item.children = this.fixSlot(item.children)
          }
        } else {
          this.fixSlot(item.children)
        }
        return item
      })
    },
    // 给树数据中的部门添加禁选属性
    renderTreeNodes (data) {
      const setData = data.map((item) => {
        // 根据名称进行排序
        if (item.children && item.children.length > 0) {
          item.children = item.children.sort(function (a, b) {
            return a.name.localeCompare(b.name)
          })
        }
        if (item.type !== this.type) {
          item.disabled = true
          item.children && this.renderTreeNodes(item.children)
        }
        return item
      })
      return setData
    },
    // 通过key 获取树节点信息
    recursiveFilter (tree, keys) {
      const data = tree.filter(item => item.id == keys)
      if (data.length != 0) {
        this.treeInfo = data[0]
      } else {
        tree.map(item => {
          if (item.children) {
            // 递归循环
            this.recursiveFilter(item.children, keys)
          }
        })
      }
      return data
    },
     // 确认分派
    async saveAssign () {
      if (!this.selectAssignData) {
        this.$message.warning('请勾选数据')
        return
      }
      if (!this.personParam.firstPersonId) {
        this.$message.warning('请选择承办人')
        return
      }
      if (!this.personParam.secondPersonId) {
        this.$message.warning('请选择协办人')
        return
      }
      if (!this.personParam.thirdPersonId) {
        // this.$message.warning('请选择辅助人')
        // return
        this.personParam.thirdPersonId = ''
        this.personParam.thirdPersonName = ''
      }
      // 1. 保存第一第二审查人信息
      const ids = this.selectAssignData.map((data) => data.id)
      const taskids = this.selectAssignData.map((data) => data.id_)

      const savem = this.$message.loading('正在分派中...', 0)
      this.confirmLoading = true
      const res = await updateFirstAndSecondPerson(
        ids,
        this.personParam.firstPersonId,
        this.personParam.firstPersonName,
        this.personParam.secondPersonId,
        this.personParam.secondPersonName,
        this.personParam.thirdPersonId,
        this.personParam.thirdPersonName
      ).finally(() => {
        setTimeout(savem, 0)
      })
      if (res.code == 0) {
          // 2、完结当前的分派环节的任务
          new Promise(async (resolve) => {
            if (taskids && taskids.length > 0) {
              // 调用分派接口
              const { code } = await claimTaskBatch(taskids, this.personParam.firstPersonId)
              if (code == 0) {
                console.log('操作成功')
              } else {
                console.log('操作失败')
              }
            }
            resolve()
          }).then(() => {
            this.queryUndoList()
          }).finally(() => {
            this.confirmLoading = false
            setTimeout(savem, 0)
          })
      } else {
        this.$message.error('案件分派失败')
      }
    },
    // 确认退回
    async saveRollBack () {
      if (!this.rollBackData) {
        this.$message.warning('请勾选数据')
        return
      }
      // 1. 保存第一第二审查人信息
      const ids = this.rollBackData.map((data) => data.id)
      const taskids = this.rollBackData.map((data) => data.id_)
      const savem = this.$message.loading('正在退回中...', 0)
      this.confirmLoading = true
      const res = await resetFirstAndSecondPerson(ids).finally(() => {
        setTimeout(savem, 0)
      })
      if (res.code == 0) {
          // 2、完结当前的分派环节的任务
          new Promise((resolve) => {
            if (taskids && taskids.length > 0) {
              taskids.forEach(async taskid => {
                // 调用退回分派接口
                const { code } = await cleanClaimTask(taskid)
                if (code == 0) {
                  console.log('操作成功')
                } else {
                  console.log('操作失败')
                }
                resolve()
              })
            }
          }).then(() => {
            this.queryUndoList()
          }).finally(() => {
            this.confirmLoading = false
            setTimeout(savem, 0)
          })
      } else {
        this.$message.error('案件退回失败')
      }
    },

    onOpenChange (openKeys) {
       console.log(openKeys, this.$route.path)
        const latestOpenKey = openKeys.find((key) => this.openKeys.indexOf(key) === -1)
        console.log(latestOpenKey, this.rootSubmenuKeys.indexOf(latestOpenKey) === -1)
        if (this.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
            this.openKeys = openKeys
        } else {
            this.openKeys = latestOpenKey ? [latestOpenKey] : []
        }
    },

    onChange (nextTargetKeys, direction, moveKeys) {
      console.log(nextTargetKeys, direction, moveKeys)
      this.selectAssignData = []
      this.rollBackData = []
      if (direction === 'right') {
        this.selectAssignData = this.assignData.filter(el => moveKeys.includes(el.id))
        this.saveAssign()
      } else {
        this.rollBackData = this.assignData.filter(el => moveKeys.includes(el.id))
        this.saveRollBack()
      }
    },

    triggerDisable (disabled) {
      this.disabled = disabled
    },
    // 搜索框
    handleSearch (dir, value) {
        console.log('search:', dir, value)
    },
    getRowSelection ({ disabled, selectedKeys, itemSelectAll, itemSelect }) {
      return {
        getCheckboxProps: item => ({ props: { disabled: disabled || item.disabled } }),
        onSelectAll (selected, selectedRows) {
          if (selected == true) {
            const treeSelectedKeys = selectedRows.filter((item) => !item.disabled).map(({ key }) => key)
            itemSelectAll(treeSelectedKeys, selected)
        } else if (selected == false) {
            const treeSelectedKeys = this.selectedRowKeys
            itemSelectAll(treeSelectedKeys, selected)
        }
        },
        onSelect ({ key }, selected) {
          itemSelect(key, selected)
        },
        selectedRowKeys: selectedKeys
      }
    }
  }
}
</script>

<style lang="less" scoped>
::v-deep .ant-tabs-tab:hover {
  color: inherit !important;
}
::v-deep .ant-tabs-nav-scroll {
  margin-left: 20px;
}
::v-deep .accept_main_tip_label_div {
  width: 300px !important;
}
::v-deep .ant-form-item-label {
  margin: 0px 8px;
}
::v-deep .ant-tabs-bar {
  margin-bottom: 0px;
}
::v-deep .ant-tabs-nav .ant-tabs-tab {
  font-family: PingFang SC;
  font-weight: 500;
  font-size: 16px;
  margin: 0 16px 10px 0;
  line-height: 0px;
}
::v-deep .ant-tabs-nav-scroll {
  background: white;
  padding-left: 10px;
  margin-left: 0px;
}

::v-deep .ant-tabs-nav-wrap {
  display: inherit;
}

::v-deep .ant-transfer-list-header-title {
  float: left;
  margin-right: 10px;
  position: unset;
  visibility: visible !important;
}

::v-deep .ant-transfer-list-header {
  font-weight: bold;
  font-size: 14px;
  line-height: 16px;
  height: 40px;
  display: flex;
  align-items: center;
}
::v-deep .ant-transfer-list-header > span:nth-child(1) {
  visibility: hidden;
}

::v-deep .ant-transfer-operation {
  .ant-btn:nth-child(1) {
    height: 32px;
  }
  .ant-btn:nth-child(2) {
    background-color: #fff !important;
    opacity: 0.8 !important;
    color: #0072c6 !important;
    border: 1px solid #0072c6 !important;
    margin-top: 32px;
    height: 32px;
  }
}
.assign-titie-div {
  display: flex;
  align-items: center;
  flex-direction: column;
  width: 100%;
}
.assign-tiltle-div-label {
  display: flex;
  align-items: center;
  width: 100%;
  margin: 10px 0px;

  font-family: PingFang SC;
  font-weight: bold;
  font-size: 18px;
  color: #000000;
  line-height: 5px;
}
.assign-tiltle-div-operate {
  display: flex;
  align-items: center;
  width: 100%;
  margin: 16px 0px;
  flex-direction: column;

  ::v-deep .ant-form-item-label {
    text-align: right;
  }

  ::v-deep .ant-form-inline {
    width: 240px;
  }
}

.assign-operate-div {
  width: 100%
}

.assign-operate-left {
  display: flex;
  align-items: center;
  width: 40%
}
.assign-operate-mid {
  display: flex;
  align-items: center;
  width: 20%
}
.assign-operate-right {
  display: flex;
  align-items: center;
  width: 40%
}

::v-deep .ant-transfer {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}
::v-deep .ant-transfer-list {
  width: 45% !important;
}
::v-deep .ant-transfer-operation {
  width: 10% !important;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
</style>
